<template>
  <Drawer
    v-model:visible="visible"
    class="custom-class"
    :title="title"
    :width="title !== '查看详情' ? '50%' : '33%'"
    :destroyOnClose="true"
    placement="right"
  >
    <Form :model="form" ref="formRef" :label-col="{ style: { width: '150px' } }">
      <FormItem
        label="应用"
        name="appId"
        :rules="title !== '新增套餐' ? [] : [{ required: true, message: '请选择应用' }]"
      >
        <template v-if="title !== '新增套餐'">{{ form.appName }}</template>
        <template v-else>
          <Select v-model:value="form.appId" placeholder="请选择应用" :disabled="disable">
            <SelectOption v-for="option in selectList" v-bind:key="option.id" :value="option.id"
              >{{ option.name }}
            </SelectOption>
          </Select>
        </template>
      </FormItem>
      <FormItem label="架构" name="architecture">
        <template v-if="title !== '新增套餐'">{{ form.architecture }}</template>
        <template v-else><Input v-model:value="form.architecture" disabled> </Input></template>
      </FormItem>
      <FormItem label="是否集成云商店" name="ifIntegrateCm">
        <template v-if="title !== '新增套餐'">{{ form.ifIntegrateCm ? '是' : '否' }}</template>
        <template v-else><Input v-model:value="form.ifIntegrateCmStr" disabled> </Input></template>
      </FormItem>
      <FormItem
        label="套餐类型"
        name="type"
        :rules="title === '查看详情' ? [] : [{ required: true, message: '请输入套餐类型' }]"
      >
        <template v-if="title == '查看详情'">{{ form.type }}</template>
        <template v-else><Input v-model:value="form.type" placeholder="请输入套餐类型" /></template>
      </FormItem>
      <FormItem
        label="数据库多租模式"
        name="dbMultiTenantMode"
        :rules="title === '查看详情' ? [] : [{ required: true, message: '请输入数据库多租模式' }]"
      >
        <template v-if="title == '查看详情'">{{ form.dbMultiTenantMode }}</template>
        <template v-else
          ><Select v-model:value="form.dbMultiTenantMode" placeholder="请选择数据库多租模式" @change="dbModeChange">
            <SelectOption v-for="option in dbMultiTenantModeList" v-bind:key="option.code" :value="option.code"
              >{{ option.label }}
            </SelectOption>
          </Select></template
        >
      </FormItem>
      <FormItem
        label="应用多租模式"
        name="appMultiTenantMode"
        :rules="title === '查看详情' ? [] : [{ required: true, message: '请输入应用多租模式' }]"
        ><template v-if="title == '查看详情'">{{ form.appMultiTenantMode }}</template>
        <template v-else
          ><Select v-model:value="form.appMultiTenantMode" placeholder="请选择应用多租模式" disabled>
            <SelectOption v-for="option in appMultiTenantModeList" v-bind:key="option.code" :value="option.code"
              >{{ option.label }}
            </SelectOption>
          </Select></template
        >
      </FormItem>

      <FormItem
        label="应用资源"
        name="resourceIdList"
        v-if="flag"
        :rules="
          title === '查看详情' || form.architecture !== '微服务' ? [] : [{ required: true, message: '请选择应用资源' }]
        "
      >
        <Tree
          :showLine="false"
          checkable
          :fieldNames="{ key: 'id', title: 'resourceName', children: 'children' }"
          style="font-weight: bolder; text-align: right"
          v-model:checkedKeys="form.resourceIdList"
          :tree-data="treeData"
          :autoExpandParent="false"
          checkStrictly
          :disabled="title == '查看详情' ? true : false"
          @check="handleSelect"
        >
          <template #title="{ title, type }">
            <span>
              <Tag color="pink" v-if="type === 'MENU'">{{ type }}</Tag>
              <Tag color="blue" v-if="type === 'ELEMENT'">{{ type }}</Tag>
              {{ title }}
            </span>
          </template>
        </Tree>
      </FormItem>

      <FormItem
        label="是否支持文件系统"
        name="ifSupportFileSystem"
        :rules="title === '查看详情' ? [] : [{ required: true, message: '必填项' }]"
        ><template v-if="title == '查看详情'">{{ form.ifSupportFileSystem ? '是' : '否' }}</template
        ><template v-else>
          <Switch
            v-model:checked="form.ifSupportFileSystem"
            checked-children="I"
            un-checked-children="O"
            :checkedValue="true"
            :unCheckedValue="false"
            :defaultChecked="false"
            @change="ifSupportFileSystemChange"
        /></template>
      </FormItem>
      <FormItem
        label="是否支持扩容"
        name="isExpand"
        :rules="title === '查看详情' ? [] : [{ required: true, message: '必填项' }]"
        ><template v-if="title == '查看详情'">{{ form.isExpand ? '是' : '否' }}</template
        ><template v-else>
          <Switch
            v-model:checked="form.isExpand"
            checked-children="I"
            un-checked-children="O"
            :checkedValue="true"
            :unCheckedValue="false"
            :defaultChecked="false"
            :disabled="isExpandDisabled"
        /></template>
      </FormItem>
      <FormItem
        label="是否支持License管理"
        name="ifSupportLicenseMgmt"
        :rules="title === '查看详情' ? [] : [{ required: true, message: '必填项' }]"
        ><template v-if="title == '查看详情'">{{ form.ifSupportLicenseMgmt ? '是' : '否' }}</template
        ><template v-else>
          <Switch
            v-model:checked="form.ifSupportLicenseMgmt"
            checked-children="I"
            un-checked-children="O"
            :checkedValue="true"
            :unCheckedValue="false"
            :defaultChecked="false"
            :disabled="dynamicDisabled"
        /></template>
      </FormItem>

      <div v-if="dynamicShow && title !== '查看详情'">
        <FormItem label="云商店产品规格标识" name="skuCode">
          <Input v-model:value="form.skuCode" placeholder="请输入云商店skuCode" />
        </FormItem>

        <FormItem label="云市场产品Id">
          <Input v-model:value="form.productIds[0]" placeholder="请输入云商店ProductId" />
        </FormItem>
        <Space
          v-for="(sight, index) in form.itemIds"
          :key="sight.id"
          align="baseline"
          style="display: flex; margin-bottom: 8px"
        >
          <MinusCircleOutlined style="margin-left: 120px" @click="remove(sight)" />
          <FormItem>
            <Input
              v-model:value="form.itemIds[index].productId"
              placeholder="请输入云市场ProductId"
              style="margin-left: 9px; width: 430%"
            />
          </FormItem>
        </Space>
        <FormItem>
          <Button block style="width: 120%; margin-right: 8px" type="dashed" @click="add">
            <PlusOutlined />
            添加云市场ProductId
          </Button>
        </FormItem>
      </div>
    </Form>

    <div class="absolute bottom-10 right-8" v-if="title !== '查看详情'">
      <Button style="margin-right: 8px; font-weight: bolder" @click="onClose">取消</Button>
      <Button type="primary" style="font-weight: bolder" @click="onSubmit">确定</Button>
    </div>
  </Drawer>
</template>

<script lang="ts" setup>
/* eslint-disable max-lines-per-function */
import {
  Drawer,
  Button,
  Form,
  FormItem,
  Input,
  Select,
  Space,
  Tag,
  Switch,
  SelectOption,
  TreeProps,
  Tree,
} from 'ant-design-vue';
import { nextTick, ref, toRaw, watch } from 'vue';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { getAppMultiTenantMode, getDbMultiTenantMode, getTenantSideApps } from '/@/api/deployment-center/deployTask';
import {
  addOrUpdateInstance,
  getMenuAndElementResourceTree,
  getProductIdBySkuCode,
  getPackageDetail,
} from '/@/api/system-mgmt/instance-mgmt/instance';

const dynamicDisabled = ref(false);
const dynamicShow = ref(false);
const emit = defineEmits(['success']);
const visible = ref(false);
const formRef = ref();
const selectList = ref([]);
const title = ref();
const disable = ref(true);
const skucode = ref();
const appMultiTenantModeList = ref([]);
const dbMultiTenantModeList = ref([]);
const treeData = ref<TreeProps['treeData']>([]);
const flag = ref(false);

let form = ref<Record<string, any>>({
  ifSupportFileSystem: false,
  ifSupportLicenseMgmt: false,
  isExpand: false,
  productIds: [],
  itemIds: [],
});
const isExpandDisabled = ref(false);
watch(
  () => form.value.appId,
  async () => {
    selectList.value.forEach((item) => {
      if (form.value.appId === item.id) {
        form.value.architecture = item.architecture;
        form.value.ifIntegrateCm = item.ifIntegrateCm;
        form.value.ifIntegrateCmStr = item.ifIntegrateCm ? '是' : '否';
      }
    });
    if (form.value.architecture === '微服务') {
      form.value.isExpand = false;
      isExpandDisabled.value = true;
      form.value.ifSupportLicenseMgmt === false;
      dynamicDisabled.value = true;
    } else {
      if (form.value.ifSupportFileSystem) {
        isExpandDisabled.value = false;
      }
      dynamicDisabled.value = false;
    }
    if (disable.value === true) {
      if (form.value.ifIntegrateCm === true) {
        dynamicShow.value = true;
        form.value.productIds = [];
        form.value.itemIds = [];
        nextTick(async () => {
          getProductIdBySkuCode({ skucode: skucode.value }).then((res) => {
            for (let i = 0; i < res.length; i++) {
              if (i === 0) {
                form.value.productIds.push(res[i]);
              } else {
                form.value.itemIds.push({
                  productId: res[i],
                });
              }
            }
          });
        });
      } else {
        dynamicShow.value = false;
        form.value.skuCode = undefined;
        form.value.productIds = undefined;
        form.value.itemIds = undefined;
      }
    } else if (disable.value === false) {
      if (form.value.ifIntegrateCm === true) {
        dynamicShow.value = true;
        form.value.skuCode = undefined;
        form.value.itemIds = [];
      } else {
        dynamicShow.value = false;
        form.value.skuCode = undefined;
        form.value.productIds = undefined;
        form.value.itemIds = undefined;
      }
    }
  }
);

const ifSupportFileSystemChange = (value) => {
  if (value == true) {
    if (form.value.architecture == '单体') {
      isExpandDisabled.value = false;
    } else {
      isExpandDisabled.value = true;
      form.value.isExpand = false;
    }
  }
};

const dbModeChange = (value) => {
  switch (value) {
    case 'COLUMN':
      form.value.appMultiTenantMode = 'SHARED';
      break;
    case 'SCHEMA':
      form.value.appMultiTenantMode = 'NAMESPACE';
      break;
    case 'DATASOURCE':
      form.value.appMultiTenantMode = 'NAMESPACE';
      break;
  }
};

// 动态增减表单
function add() {
  form.value.itemIds.push({
    productId: '',
  });
}

function remove(item: string) {
  let index = form.value.itemIds.indexOf(item);
  if (index !== -1) {
    form.value.itemIds.splice(index, 1);
  }
}
const openDetailDrawer = async (record) => {
  visible.value = true;
  title.value = '查看详情';
  form.value = await getPackageDetail({ id: record.id });
};
const openDrawer = async (params?: any) => {
  visible.value = true;
  flag.value = false;
  skucode.value = params === undefined || params.skuCode === undefined ? '' : params.skuCode;
  form.value = {
    ifSupportFileSystem: false,
    ifSupportLicenseMgmt: false,
    isExpand: false,
    productIds: [],
    itemIds: [],
  };

  selectList.value = await getTenantSideApps([3]);
  appMultiTenantModeList.value = await getAppMultiTenantMode();
  dbMultiTenantModeList.value = await getDbMultiTenantMode();

  formRef.value.resetFields();
  disable.value = true;
  if (params !== undefined) {
    title.value = '编辑套餐';
    form.value = await getPackageDetail({ id: params.id });
  } else {
    title.value = '新增套餐';
    disable.value = false;
  }
};

const onClose = () => {
  formRef.value.resetFields();
  flag.value = false;
  visible.value = false;
};

const onSubmit = () => {
  let params;
  formRef.value.validate().then(async () => {
    params = toRaw(form);
    params.value.multiTenantModel = params.value.dbMultiTenantMode + '_' + params.value.appMultiTenantMode;
    await addOrUpdateInstance(params.value);
    onClose();
    emit('success');
  });
};

const getNodeChildrenIdList = (node) => {
  let _nodeList = [];

  function traverse(node, nodeList) {
    if (node.children) {
      for (let child of node.children) {
        _nodeList.push(child.id);
        if (child.children) {
          traverse(child, nodeList);
        }
      }
    }
  }

  traverse(node, _nodeList);

  return _nodeList;
};

const getParentNode = (node) => {
  let _parentList = [];

  function findParents(node, parentList) {
    if (node.parent) {
      parentList.push(node.parent.node.id);
      if (node.parent.parent) {
        findParents(node.parent, parentList);
      }
    }
  }
  findParents(node, _parentList);
  return _parentList;
};

const handleChecked = (node) => {
  const childrenNodeIdList = getNodeChildrenIdList(node);
  const parentNodeIdList = getParentNode(node);
  const { checked } = form.value.resourceIdList;
  form.value.resourceIdList = [...checked, ...childrenNodeIdList, ...parentNodeIdList];
};
const handleDischecked = (node) => {
  const childrenNodeIdList = getNodeChildrenIdList(node);
  const { checked } = form.value.resourceIdList;
  form.value.resourceIdList = checked.filter((item) => !childrenNodeIdList.includes(item));
};

const handleSelect = (value, ...rest) => {
  const { checked, node } = rest[0];
  if (checked) {
    handleChecked(node);
  } else {
    handleDischecked(node);
  }
};

watch(
  () => form.value.appId,
  async () => {
    if (form.value.appId !== undefined) {
      flag.value = true;
      treeData.value = await getMenuAndElementResourceTree({ appId: form.value.appId });
    }
  }
);

defineExpose({ openDrawer, openDetailDrawer });
</script>
